package com.suxin.http.request;

import com.alibaba.nacos.common.utils.JacksonUtils;
import com.suxin.http.HttpClientConfig;
import com.suxin.http.model.RequestHttpEntity;
import com.suxin.http.response.HttpClientResponse;
import com.suxin.http.response.JdkHttpClientResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Map;

/**
 * @author Tang
 * @classname JdkHttpClientRequest
 * @description [  ]
 * @date 2023/3/3 16:37
 */
public class JdkHttpClientRequest implements HttpClientRequest {

    private final HttpClientConfig httpClientConfig;

    public JdkHttpClientRequest(HttpClientConfig httpClientConfig) {
        this.httpClientConfig = httpClientConfig;
    }

    @Override
    public HttpClientResponse execute(URI uri, String method, RequestHttpEntity requestHttpEntity) throws Exception {
        final HttpURLConnection urlConnection = (HttpURLConnection)uri.toURL().openConnection();
        urlConnection.setConnectTimeout(this.httpClientConfig.getConnectTimeout());
        urlConnection.setReadTimeout(this.httpClientConfig.getReadTimeOutMillis());
        urlConnection.setRequestMethod(method);
        urlConnection.setDoOutput(true);
        // 设置 header
        final Map<String, String> header = requestHttpEntity.getHeader().getHeader();
        for (String key : header.keySet()) {
            urlConnection.addRequestProperty(key,header.get(key));
        }
        // post 请求
        final Object body = requestHttpEntity.getBody();
        if (body != null && MediaType.APPLICATION_JSON_VALUE.equals(header.get(HttpHeaders.CONTENT_TYPE))) {
            final OutputStream outputStream = urlConnection.getOutputStream();
            final byte[] bytes = JacksonUtils.toJsonBytes(body);
            urlConnection.addRequestProperty(HttpHeaders.CONTENT_LENGTH,String.valueOf(bytes.length));
            outputStream.write(bytes);
            outputStream.flush();
        }
        urlConnection.connect();
        return new JdkHttpClientResponse(urlConnection);
    }

    @Override
    public void close() throws IOException {

    }
}
